package me.olook.netease.song.rank.task;

import me.olook.netease.song.rank.annotation.TimerJobTypeName;
import me.olook.netease.song.rank.biz.TimerJobService;
import me.olook.netease.song.rank.biz.WeiboUserService;
import me.olook.netease.song.rank.entity.TimerJob;
import me.olook.netease.song.rank.entity.WeiboUser;
import me.olook.netease.song.rank.util.WeiboApiImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Optional;

/**
 * @author zhaohw
 * @date 2018-05-29 10:59
 */
@TimerJobTypeName(value = "Web关键词搜索")
public class WebWeiboUserTask implements Job {

    @Autowired
    private WeiboApiImpl weiboApi;

    @Autowired
    private WeiboUserService weiboUserService;

    @Autowired
    private TimerJobService timerJobService;

    private static Logger log = LoggerFactory.getLogger(WebWeiboUserTask.class);

    private static boolean LOGIN_FLAG = false;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getTrigger().getJobKey();

        if(!LOGIN_FLAG){
            weiboApi.loginInit();
            LOGIN_FLAG = true;
        }

        //默认搜索前15页
        int pageNum = 20;

        Optional<TimerJob> timerJob = timerJobService.findByNameAndGroup(jobKey.getName(),jobKey.getGroup());
        if(!timerJob.isPresent()){
            return;
        }
        long start = System.currentTimeMillis();
        int count = 0;
        for(int i = 1; i < pageNum; i++){
            String html = weiboApi.webSearch(timerJob.get().getJobParam(),i);
            List<WeiboUser> users = weiboApi.getWeiboUsersFromSearch(html);
            count += users.size();
            users.forEach(p->{
                p.setAddBy(timerJob.get().getJobParam());
                weiboUserService.save(p);
            });
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("任务：{} 获取数据：{} 条 , 耗时：{} ",timerJob.get().getJobName() ,count,System.currentTimeMillis()-start);

    }
}
